<template>
  <div class="app-container">
    <div class="filter-container">
      <el-row :gutter="10">
        <el-col :xs="24" :sm="24" :md="12" :lg="16" :xl="16">
        <el-input v-model="listQuery.parentId" clearable class="filter-item" placeholder="上级部门" @keyup.enter.native="fetchListData"></el-input>
        <el-input v-model="listQuery.name" clearable class="filter-item" placeholder="部门名称" @keyup.enter.native="fetchListData"></el-input>
        </el-col>
        <el-col :xs="24" :sm="24" :md="12" :lg="8" :xl="8" style="text-align: right">
          <el-button v-waves class="filter-button" icon="el-icon-back" @click="$router.back()">返回</el-button>
          <el-button v-waves type="primary" class="filter-button" icon="el-icon-search" @click="fetchListData">搜索</el-button>
          <el-button v-waves type="primary" class="filter-button" icon="el-icon-edit" v-permission="['security:sysDepartment:add']" @click="handleCreateSysDepartment(listQuery.parentId)">新建</el-button>
        </el-col>
      </el-row>
    </div>
    <div class="table-container">
      <tree-table-list ref="table" url="/security/sysDepartment" :query="listQuery" :columns="columns" :format="format">
        <template slot="actions" slot-scope="scope">
          <el-button v-waves v-permission="['security:sysDepartment:edit']" type="primary" @click="handleCreateSysDepartment(scope.row.id)">新建子类</el-button>
          <el-button v-waves v-permission="['security:sysDepartment:edit']" type="primary" @click="handleEditSysDepartment(scope.$index, scope.row)">编辑</el-button>
          <el-button v-waves v-permission="['security:sysDepartment:delete']" type="danger" @click="handleDeleteSysDepartment(scope.$index, scope.row)">删除</el-button>
        </template>
      </tree-table-list>

      <el-dialog :title="dialogTextMap[dialogStatus]" :visible.sync="createDialogVisible" :width="$store.state.app.device === 'mobile' ? '100%' : '60%'">
        <el-form ref="dataForm" :rules="rules" :model="temp" label-width="100px" label-suffix=": " :inline="true">
          <el-form-item label="部门名称" prop="name">
            <el-input clearable class="form-item" v-model="temp.name" placeholder="部门名称"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button v-waves @click="createDialogVisible = false">取消</el-button>
          <el-button v-waves type="primary" v-permission="['security:sysDepartment:add' || 'sysDepartment:edit ']" @click="dialogStatus==='create'?handleAddSysDepartment():handleUpdateSysDepartment()">提交</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import permission from '@/directive/permission/index.js' // 权限判断指令
import waves from '@/directive/waves' // waves directive
import { create as createSysDepartment, update as updateSysDepartment, deleteById as deleteSysDepartment } from '@/api/security/sysDepartment'
import { mapGetters } from 'vuex'
import TreeTableList from '@/components/TreeTableList'
export default {
  name: 'SysDepartment',
  components: { TreeTableList },
  directives: { permission, waves },
  data() {
    return {
      list: null,
      columns: [
        { key: 'name', label: '部门名称' },
        { key: 'createTime', label: '创建时间',sortable: true },
        { key: 'actions', label: '操作', width: 320, fixed: 'right', align: 'left' }
      ],
      format: {
      },
      listQuery: {
        parentId: undefined,
        name: undefined
      },
      temp: {parentId: undefined,name: undefined},
      dialogTextMap: {update: '编辑',create: '新建', detail: '详情'},
      rules: {
        parentId: [{ required: true, message: '上级部门必填!', trigger: 'change' }],
        name: [{ required: true, message: '部门名称必填!', trigger: 'blur' }],
      },
      dialogStatus: '',
      createDialogVisible: false,
    }
  },
  computed: {
    ...mapGetters([
      'name'
    ])
  },
  created() {
    const allOptions = JSON.parse(localStorage.getItem('allOptions'))
  },
  mounted() {
    this.fetchListData()
  },
  methods: {
    fetchListData() {
      this.$refs.table.fetchData(1)
    },
    reloadListData() {
      this.$refs.table.fetchData()
    },
    resetTemp() {
      this.temp = {parentId: undefined,name: undefined,}
    },
    handleCreateSysDepartment(parentId) {
      this.resetTemp()
      this.temp.parentId = parentId
      this.dialogStatus = 'create'
      this.createDialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleEditSysDepartment(index, val) {
      this.temp = Object.assign({}, val)
      this.dialogStatus = 'update'
      this.createDialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleAddSysDepartment() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const queryData = Object.assign({}, this.temp)
          queryData.status = Number(queryData.status)
          createSysDepartment(queryData).then(() => {
            // this.list.unshift(queryData)
            this.fetchListData()
            this.createDialogVisible = false
            this.$notify.success('创建成功!')
          })
        }
      })
    },
    handleUpdateSysDepartment() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp)
          updateSysDepartment(tempData).then(() => {
            this.reloadListData()
            this.createDialogVisible = false
            this.$notify.success('更新成功!')
          })
        }
      })
    },
    handleDeleteSysDepartment(index, val) {
      const self = this
      this.$confirm('确定要删除该？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteSysDepartment(val.id).then(() => {
          self.reloadListData()
          self.$notify.success('已删除!')
        })
      }).catch(() => {})
    },
  }
}
</script>

